package com.hljx.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljx.config.exception.DataException;
import com.hljx.dto.DateDTO;
import com.hljx.entity.SysHospitalArea;
import com.hljx.entity.SysItemPiont;
import com.hljx.mapper.sys.SysItemPiontMapper;
import com.hljx.service.SysItemPiontService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hljx.vo.HospitalAreasVO;
import com.hljx.vo.SysItemPiontVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 科室项目对照关系表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-01-12
 */
@Service
public class SysItemPiontServiceImpl extends ServiceImpl<SysItemPiontMapper, SysItemPiont> implements SysItemPiontService {


    @Override
    public IPage<SysItemPiontVO> listByPeriod(DateDTO dateDTO) {
        Page<SysItemPiontVO> page = new Page<>(dateDTO.getPageNum(), dateDTO.getPageSize());
        IPage<SysItemPiontVO> sysItemPiontVOIPage = baseMapper.listByPeriod(page, dateDTO);
        return sysItemPiontVOIPage;
    }

    @Override
    public boolean saveOrUpdateSysItemPiont(SysItemPiont sysItemPiont) {
        //查询历史数据判断指数是否超出
        List<SysItemPiont> list = list(Wrappers.lambdaQuery(SysItemPiont.class)
                .eq(SysItemPiont::getYDeptCode, sysItemPiont.getYDeptCode())
                .eq(SysItemPiont::getItemCode, sysItemPiont.getItemCode())
                .eq(SysItemPiont::getPeriod,sysItemPiont.getPeriod())
                .ne(sysItemPiont.getId() != null, SysItemPiont::getId, sysItemPiont.getId()));
        BigDecimal sum = list.stream().map(SysItemPiont::getPiont)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal add = sum.add(sysItemPiont.getPiont());
        if ( add.compareTo(new BigDecimal(1))==1){
            BigDecimal subtract = new BigDecimal(1).subtract(sum);
            throw new DataException("指数最大值为"+subtract,333);
        }
        return saveOrUpdate(sysItemPiont);
    }

    @Override
    public Boolean isOffsetting(Long id, int isOffsetting) {
            baseMapper.isOffsetting(id ,isOffsetting);
        return true;
    }


}
